<template>
	<div class="article-page">
		<!-- 表格数据 -->
		<div class="w-full h-[90%]">
			<RichTable
				:data="tableData"
				:fields="fields"
				@on-search="handleSearch"
				@on-delete="handleBatchDelete"
				@on-selection-change="handleSelectionChange"
				@on-add="router.push('/admin/createArticle')">
				<el-table-column label="操作" fixed="right">
					<template #default="scope">
						<nuxt-link :to="`/details/${scope.row._id}`">
							<el-button link type="primary" size="small"> 查看 </el-button>
						</nuxt-link>
						<el-button
							link
							type="success"
							size="small"
							@click="router.push(`/admin/updateArticle?id=${scope.row._id}`)">
							修改
						</el-button>
						<el-button link type="danger" size="small" @click="handleDelete(scope.row._id)">
							删除
						</el-button>
					</template>
				</el-table-column>
			</RichTable>
		</div>

		<!-- 分页 -->
		<div class="flex items-center justify-between py-2">
			<div class="mr-2 flex items-center">
				<el-text type="info" size="small">选中：{{ selectList.length }}项</el-text>
			</div>
			<el-scrollbar>
				<ElsPagination
					:total="total"
					:pageSize="pageSize"
					:currentPage="currentPage"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange" />
			</el-scrollbar>
		</div>
	</div>
</template>

<script name="ArticlePage" lang="ts" setup>
import type { IArticle } from '~/server/models/article.model';
import type { TableFields } from '~/components/RichTable/types';

const router = useRouter();

// 分页
const total = ref<number>(0);
const pageSize = ref<number>(20);
const currentPage = ref<number>(1);
const handleCurrentChange = (page: number): void => {
	currentPage.value = page;
	getTableData();
};
const handleSizeChange = (size: number): void => {
	pageSize.value = size;
	getTableData();
};

// 表格数据
const tableData = ref<IArticle[]>([]);

// 表格字段
const fields: TableFields = [
	{ type: 'text', label: 'ID', prop: '_id', sortable: true },
	{ type: 'image', label: '封面', prop: 'cover' },
	{ type: 'text', label: '标题', prop: 'title' },
	{ type: 'text', label: '内容', prop: 'content' },
	{ type: 'text', label: '分类', prop: 'category' },
	{ type: 'text', label: '创建时间', prop: 'createdAt' },
	{ type: 'text', label: '更新时间', prop: 'updatedAt' },
];

// 删除
const handleDelete = (id: string): void => {
	ElMessageBox.confirm('删除后无法恢复，是否确认删除？', '警告', {
		type: 'warning',
	})
		.then(() => {
			$fetch('/api/admin/article/delete', {
				method: 'DELETE',
				query: { id },
			}).then((res: any) => {
				if (res.code === 1) {
					ElMessage.success('删除成功');
					getTableData();
				} else {
					ElMessage.error(res.message);
				}
			});
		})
		.catch(() => {
			ElMessage.info('取消删除');
		});
};

// 搜索
const handleSearch = (k: string): void => {
	getTableData(k);
};

// 批量删除
const handleBatchDelete = (): void => {
	if (selectList.value.length === 0) {
		ElMessage.warning('请先选择要删除的文章');
		return;
	}
	ElMessageBox.confirm('删除后无法恢复，是否确认删除？', '警告', {
		type: 'warning',
	})
		.then(() => {
			$fetch('/api/admin/article/delete', {
				method: 'DELETE',
				query: { id: selectList.value.map((item) => item._id).join(',') },
			}).then((res: any) => {
				if (res.code === 1) {
					ElMessage.success(res.message);
					getTableData();
				} else {
					ElMessage.error(res.message);
				}
			});
		})
		.catch(() => {
			ElMessage.info('取消删除');
		});
};

// 选中项
const selectList = ref<IArticle[]>([]);
const handleSelectionChange = (items: IArticle[]): void => {
	selectList.value = items;
};

// 获取表格数据
const getTableData = (keyword?: string): void => {
	$fetch('/api/client/article/list', {
		query: {
			keyword,
			pageSize: pageSize.value,
			currentPage: currentPage.value,
		},
	}).then((res: any) => {
		if (res.code === 1) {
			tableData.value = res.data.list.map((item: any) => {
				return {
					...item,
					category: item.category.name,
				};
			});
			total.value = res.data.total;
		} else {
			ElMessage.error(res.message);
		}
	});
};
getTableData();
</script>
